import { defineStore } from 'pinia'
// import request from '@/utils/request'
import request from '@/utils/request'
import { ApiRes, CategoryItem, SubCategory } from '@/types/data'

// 优化 ,刷新 头部导航 会白屏,定义一个跟后台一样的常量 默认展示
import { topCategory } from '../constants'
import { delay } from '@/utils/delay'
// let id = 1
// 因为需要 展示的字段 是对象中的name 属性 =>返回一个 对象
const defaultCategory = topCategory.map((item, index) => ({ id: index + '', name: item }))

const useCategory = defineStore('category', {
  state() {
    return {
      list: defaultCategory as CategoryItem[],
      topCategory: {} as CategoryItem,
      subCategory: {} as SubCategory
    }
  },
  actions: {
    async getCategory() {
      // await delay(5000) // 调试使用
      const res = await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
      // console.log(res.data.result)
      res.data.result.forEach(item => item.open = false)
      this.list = res.data.result
    },
    show(id: string) {
      const category = this.list.find(item => item.id === id)
      category!.open = true
    },
    hide(id: string) {
      const category = this.list.find(item => item.id === id)
      category!.open = false
    },
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<CategoryItem>>('/category', {
        params: { id },
      })
      // console.log(res)
      this.topCategory = res.data.result
    },
    // 2级分类数据
    async getSubCategory(id: string) {
      const res = await request.get<ApiRes<SubCategory>>('/category/sub/filter', {
        params: { id },
      })
      console.log(res.data)
      this.subCategory = res.data.result
    },





  },
  getters: {

  }
})
export default useCategory
